/**
 * Created by xmh on 2017/4/28.
 */

//自定义js库  accets/js/cedUtils.js 参考http://blog.csdn.net/cut001/article/details/70170863?winzoom=1
declare var CED: any, CryptoJS: any,NetDes:any;

import {Injectable} from '@angular/core';

@Injectable()
export class EncryptService {

  desKey: string = 'onluy'; //des加密秘钥

  constructor() {
    //console.log('Hello HttpService Provider');
  }

  //新版本des加密
  encryptByDES(str){
    console.log('req加密前:' + str);
    let enResult = NetDes.Encrypt(this.desKey,str);
    console.log('req加密后:' + enResult);
    return enResult;
  }

  //新版本des解密
  decryptByDES(str){
    console.log('resp解密前:\n' + str);

    let deResult:string = NetDes.Decrypt(this.desKey,str );
    console.log('resp解密后:'+ deResult.length+'\n' + deResult);

    //解密后json反编译错误
    for(let i=0;i<10;i++) {
      let laststr = NetDes.stringToHex(deResult.substr(deResult.length - 1));
      console.log('laststr:' + laststr);
      if (laststr == '00') {
        deResult = deResult.substr(0, deResult.length - 1)
      }
      else
        break;
    }

    try {
      deResult = JSON.parse(deResult);
    }catch (e){
       try {
         deResult = eval("(" + deResult + ")");
       }
       catch (e1){
         console.log('resp解密后转json异常:'+e1+ JSON.stringify(e1));
       }
    }
    return  deResult ;
  }
}
